package com.zjitc.controller;

import com.google.gson.Gson;
import com.zjitc.model.ChatItem;
import com.zjitc.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/5/3 0003
 * @description:
 */
@Controller
public class ChartControl {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello2() {
        return "hello....";
    }

    @RequestMapping(value = "/chat")
    @ResponseBody
    public String sengMessage(@RequestParam(name = "msg") String msg, HttpServletRequest request,
                              HttpSession session) {
        ServletContext context = request.getServletContext();
//        Synchronized  同步机制，
        Map<Integer, ChatItem> chatItemMap =
                (Map<Integer, ChatItem>) context.getAttribute("chatMap") == null ?
                        Collections.synchronizedMap(new LinkedHashMap<Integer, ChatItem>())
                        : (Map<Integer, ChatItem>) context.getAttribute("chatMap");
        ChatItem item = new ChatItem();
        item.setMessage(msg);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String s = dateFormat.format(date);
        item.setDate(s);
        User user = (User) session.getAttribute("user");
        item.setUsername(user.getUsername());
        item.setUid(user.getUid());
        Integer count = (Integer) context.getAttribute("count") == null ? 0
                : (Integer) context.getAttribute("count");
        count = count + 1;
        item.setcCount(count);
        synchronized (chatItemMap) {
            chatItemMap.put(count, item);
        }
        context.setAttribute("count", count);
        context.setAttribute("chatMap", chatItemMap);
        return Integer.toString(1);
    }

    @RequestMapping(value = "/getChatMsg", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getChatMsg(int count, HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        Map<Integer, ChatItem> chatItemMap = (Map<Integer, ChatItem>) context.getAttribute("chatMap");
        if (chatItemMap == null) {
            return null;
        } else {
            List<ChatItem> list = new ArrayList<>();
            for (Map.Entry<Integer, ChatItem> entry : chatItemMap.entrySet()) {
                if (entry.getKey() > count) {
                    list.add(entry.getValue());
                }
            }
            Gson gson = new Gson();
            String s = gson.toJson(list);
            return s;
        }
    }
}
